//
//  NSImage+Color.swift
//  ImageColorPicker
//
//  Created by tanwz on 16/6/2.
//  Copyright © 2016年 tanwz. All rights reserved.
//

import Foundation
import Cocoa

extension NSImage {
    func colorAtPoint(point: NSPoint) -> NSColor? {
        if !CGRectContainsPoint(CGRectMake(0, 0, size.width, size.height), point) {
            return nil
        }
        
        let width = Int(size.width)
        let height = Int(size.height)
        
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let pixelData = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
        let ctx = CGBitmapContextCreate( pixelData, 1, 1, 8, 4, colorSpace, CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue)
        CGContextSetBlendMode(ctx, CGBlendMode.Copy)
        
        CGContextTranslateCTM(ctx, -point.x, -point.y)
        CGContextDrawImage(ctx, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), CGImageForProposedRect(nil, context: nil, hints: nil))
        
        let red     = CGFloat(pixelData[0]) / 255.0
        let green   = CGFloat(pixelData[1]) / 255.0
        let blue    = CGFloat(pixelData[2]) / 255.0
        let alpha   = CGFloat(pixelData[3]) / 255.0
        return NSColor(deviceRed: red, green: green, blue: blue, alpha: alpha)
    }
}
